package com.playball.lottery.frm.yhzx;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.R;
import com.playball.lottery.fragment.frm.Tab1Fragment;
import com.playball.lottery.nt.GetJsonData;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 推广联盟
 */
public class MyCmdQRCode extends Activity{
	private final String murl= Tab1Fragment.mUrl;
	private String qrImgPath = "";
	
	ImageView iv_qrcode;
	TextView tv_tips;
	Button btn_share_2_wx;

	private Context mContext;
	Bitmap qrbitmap;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.my_cmd_qr);
		titleBar();
		mContext = this;
		tv_tips = (TextView) findViewById(R.id.tv_qr_tips);
		iv_qrcode = (ImageView) findViewById(R.id.img_qrcode);
		qrImgPath ="http://"+murl+"/user/register/wap/index.html?i="+ApplicationData.getInstance().getUserID();
		
		final String filePath = getFileRoot(this) + File.separator
                + "qr_1" + ApplicationData.getInstance().getUserName() + ".jpg";
		tv_tips.setText("正在生成二维码......");
			 //二维码图片较大时，生成图片、保存文件的时间可能较长，因此放在新线程中  
	        new Thread(new Runnable() {  
	            @Override  
	            public void run() {  
	                boolean success = createQRImage(qrImgPath, 800, 800,  
	                		BitmapFactory.decodeResource(getResources(), R.drawable.app_icons),
	                        filePath);  
	                	
	                if (success) {  
	                    runOnUiThread(new Runnable() {  
	                        @Override  
	                        public void run() {
	                        	qrbitmap = BitmapFactory.decodeFile(filePath);
	                        	btn_share_2_wx.setVisibility(View.VISIBLE);
	                            iv_qrcode.setImageBitmap(BitmapFactory.decodeFile(filePath));  
	                            tv_tips.setText("扫描二维码，然后在打开的网页中注册，即可让您的朋友一起加入彩店通！");
	                        }  
	                    });  
	                }  
	            }  
	        }).start(); 
	        
	        
	        btn_share_2_wx = (Button) findViewById(R.id.btn_share_2_wx);
	        btn_share_2_wx.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					shareImage(qrbitmap);
				}
			});
	        
	}
	public void shareImage(Bitmap bitmap) {
	    try {
			startActivity(Intent.createChooser(
					new Intent(Intent.ACTION_SEND)
									.setType("text/plain")
									.putExtra(Intent.EXTRA_TEXT,
											"点击:"+qrImgPath+"注册加入彩店通！彩票、六合彩、足球平台首选，提现快，开奖快！下载地址:http://tcaio2o.com/APP/downApp.htm")
									.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), "分享给您的好友"));
	    	
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}
	
	// TitleBar标题栏
	public void titleBar() {
		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText("推广链接");
		TextView back = (TextView) findViewById(R.id.top_title_back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MyCmdQRCode.this.finish();
			}
		});
	}
	
	//文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }
    
    /**
     * 生成二维码Bitmap
     *
     * @param content   内容
     * @param widthPix  图片宽度
     * @param heightPix 图片高度
     * @param logoBm    二维码中心的Logo图标（可以为null）
     * @param filePath  用于存储二维码图片的文件路径
     * @return 生成二维码及保存文件是否成功
     */
    public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
        try {
            if (content == null || "".equals(content)) {
                return false;
            }
            //配置参数
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //设置空白边距的宽度
//            hints.put(EncodeHintType.MARGIN, 2); //default is 4
            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
            if (logoBm != null) {
                bitmap = addLogo(bitmap, logoBm);
            }
            //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的，内存消耗巨大！
            return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    /** 
     * 在二维码中间添加Logo图案 
     */  
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {  
        if (src == null) {  
            return null;  
        }  
        if (logo == null) {  
            return src;  
        }  
        //获取图片的宽高  
        int srcWidth = src.getWidth();  
        int srcHeight = src.getHeight();  
        int logoWidth = logo.getWidth();  
        int logoHeight = logo.getHeight();  
        if (srcWidth == 0 || srcHeight == 0) {  
            return null;  
        }  
        if (logoWidth == 0 || logoHeight == 0) {  
            return src;  
        }  
        //logo大小为二维码整体大小的1/6  
        float scaleFactor = srcWidth * 1.0f / 6 / logoWidth;  
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);  
        try {  
            Canvas canvas = new Canvas(bitmap);  
            canvas.drawBitmap(src, 0, 0, null);  
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);  
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);  
            canvas.save(Canvas.ALL_SAVE_FLAG);  
            canvas.restore();  
        } catch (Exception e) {  
            bitmap = null;  
            e.getStackTrace();  
        }  
        return bitmap;  
    }  
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
				this.finish();
				return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	};
	
}
